const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
// const bodyparser = require('koa-bodyparser')
const logger = require("koa-logger");
const koaBody = require("koa-body");
// 跨域
const cors = require("koa2-cors");
// 连接数据库
const dbConnection = require("./mongodb/mongoose");

// error handler
onerror(app);

app.use(cors());
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "ejs"
  })
);

app.use(
  koaBody({
    multipart: true, //是否支持 multipart-formdate 的表单
    formidable: {
      keepExtensions: true, // 保持文件的后缀
      maxFileSize: 500 * 1024 * 1024 // 设置上传文件大小最大限制，默认5M
    }
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
const index = require("./routes/index");
const users = require("./routes/users");
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());

const user_router = require("./routes/api/user_router");
const course_router = require("./routes/api/course_router");
const school_router = require("./routes/api/school_router");
const example_router = require("./routes/api/example_router");

app.use(user_router.routes()).use(user_router.allowedMethods());
app.use(course_router.routes()).use(course_router.allowedMethods());
app.use(school_router.routes()).use(school_router.allowedMethods());
app.use(example_router.routes()).use(example_router.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
